package com.eco.netty;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.eco.entity.LightB;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xulinyu
 * @CreateTime: 2024-08-14
 */
@Data
@Component
@Slf4j
public class NettyClientConfig {

    @Value("${sensor.config:}")
    private String sensorConfig;

    private List<GenericNettyClient> clientList = Lists.newArrayList();

    private Map<String,GenericNettyClient> clientMap = Maps.newHashMap();

    @PostConstruct
    public void init() {
        List<LightB> lightBList = JSONUtil.toList(sensorConfig, LightB.class);
        if(CollectionUtil.isNotEmpty(lightBList)){
            lightBList.forEach(x->{
                GenericNettyClient genericNettyClient = new GenericNettyClient(x.getName(), x.getIp(), x.getPort(), x.getOnCommand(), x.getOffCommand());
                //设备集合
                clientList.add(genericNettyClient);
                //设备map
                clientMap.put(x.getName(),genericNettyClient);
                //连接设备
                genericNettyClient.connect();
            });
        }else{
            log.error("没有设备被初始化...");
        }

    }

    @PreDestroy
    public void destroy() {
        //断开连接
        clientList.forEach(GenericNettyClient::shutdown);
    }

}
